package com.atguigu.glkt.vod.controller;

import com.atguigu.glkt.exception.GlktException;
import com.atguigu.glkt.result.Result;
import com.atguigu.glkt.vod.service.VodService;
import com.atguigu.glkt.vod.utils.ConstantPropertiesUtil;
import com.atguigu.glkt.vod.utils.Signature;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

/**
 * @author ShaoXuan
 * @create 2022/1/24
 */
@Api(tags = "腾讯云点播")
@RestController
@RequestMapping("/admin/vod")

public class VodController {
    @Autowired
    private VodService vodService;

    /**
     * 返回客户端上传视频签名
     * @return
     */
    @ApiOperation("返回客户端上传视频签名")
    @GetMapping("sign")
    public Result sign(){
        Signature sign = new Signature();
        // 设置 App 的云 API 密钥
        sign.setSecretId(ConstantPropertiesUtil.ACCESS_KEY_ID);
        sign.setSecretKey(ConstantPropertiesUtil.ACCESS_KEY_SECRET);
        sign.setCurrentTime(System.currentTimeMillis() / 1000);
        sign.setRandom(new Random().nextInt(java.lang.Integer.MAX_VALUE));
        sign.setSignValidDuration(3600 * 24 * 2); // 签名有效期：2天
        try {
            String signature = sign.getUploadSignature();
            System.out.println("signature : " + signature);
            return Result.ok(signature);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlktException(20001,"获取签名失败");

        }
    }


    /**
     * 上传视频
     * @return
     */
    @ApiOperation("上传视频")
    @PostMapping("upload")
    public Result uploadVideo(@RequestParam("file") MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        String fileId = vodService.uploadVideo(inputStream, originalFilename);
        return Result.ok(fileId);
    }

    /**
     * 删除视频
     * @param videoSourceId
     * @return
     */
    @ApiOperation("删除视频")
    @DeleteMapping("remove/{videoSourceId}")
    public Result removeVideo( @PathVariable String videoSourceId) {
        vodService.removeVideo(videoSourceId);
        return Result.ok();
    }

}
